package cn.com.framework.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.com.support.context.RunData;

/**
 * 请求过滤器
 * 
 * @since 2012-3-9 上午12:47:23
 * @version 1.0
 * @author Microbun
 */
public class RequestContextFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		try {
			// 初始化RunData
			RunDataImpl.init(new RunDataImpl(request, response));

			// 转发请求
			chain.doFilter(request, response);
		} finally {

			// 清理请求
			RunDataImpl.clear();
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

	/**
	 * RunData实现类
	 * 
	 * @since 2012-3-9 下午9:51:22
	 * @version 1.0
	 * @author Microbun
	 */
	private static class RunDataImpl extends RunData {

		public RunDataImpl(ServletRequest request, ServletResponse response) {
			super(HttpServletRequest.class.cast(request),
					HttpServletResponse.class.cast(response));
		}

		private static void init(RunData rundata) {
			setRundata(rundata);
		}

		private static void clear() {
			setRundata(null);
		}

	}

}
